#include "../proto/user.pb.h"
#include "SrpcApplication.h"
#include "SrpcChannel.h"
#include "SrpcController.h"
#include <atomic>
#include <chrono>
#include <glog/logging.h>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
using namespace Suser;
void send_request(int thread_id, atomic<int> &success_count,
                  atomic<int> &fail_count) {
  UserServiceRpc_Stub stub(new SrpcChannel(false));
  // 设置RPC方法的请求参数
  LoginRequest request;
  request.set_name("zhangsan");
  request.set_pwd("123456");
  // 定义RPC方法的响应参数
  LoginResponse response;
  SrpcController controller;
  stub.Login(&controller, &request, &response, nullptr);
  // 检查是否调用成功
  if (controller.Failed()) {
    cout << "call error is: " << controller.ErrorText() << endl;
    fail_count++;
    return;
  }
  if (response.result().errorcode() == 0) {
    cout << "rpc login response success: " << response.success() << endl;
    success_count++;
  } else {
    cout << "rpc login response error: " << response.result().errormessage()
         << endl;
    fail_count++;
  }
}

int main(int argc, char **argv) {
  SrpcApplication::Init(argc, argv);
  // 创建日志对象
  google::InitGoogleLogging("MyRpc");
  FLAGS_colorlogtostderr = true; // 启用彩色日志
  FLAGS_logtostderr = true;      // 默认输出标准错误

  const int thread_count = 10;
  const int requests_per_thread = 1;
  vector<std::thread> threads;
  atomic<int> success_count{0};
  atomic<int> fail_count{0};
  auto start_time = chrono::high_resolution_clock::now();
  for (int i = 0; i < thread_count; i++) {
    threads.emplace_back(
        [argc, argv, i, &success_count, &fail_count, requests_per_thread]() {
          for (int j = 0; j < requests_per_thread; ++j) {
            send_request(i, success_count, fail_count);
          }
        });
  }
  for (auto &t : threads) {
    t.join();
  }
  auto end_time = chrono::high_resolution_clock::now();
  chrono::duration<double> elapsed = end_time - start_time;
  LOG(INFO) << "Total request:" << thread_count * requests_per_thread;
  LOG(INFO) << "Success count: " << success_count;
  LOG(INFO) << "Fail count: " << fail_count;
  LOG(INFO) << "Elapsed time: " << elapsed.count() << "s";
  LOG(INFO) << "QPS: "
            << (thread_count * requests_per_thread) / elapsed.count();
  return 0;
}
